package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;


@SuppressWarnings("serial")
public class ContactServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html");
		resp.getWriter().println("Hello, world");
		String[] check = new String[4];
		req.setAttribute("title", "Contact us");
		req.setAttribute("description", "Contact us .Show details information about a website for example : alexa, pagerank, whois, ip,  the basic assessment of the site, provide  related to the website you are viewing");
		req.setAttribute("keyword", "website,site,5ty,5ty.org,alexa,google pagerank,pagerank,whois,ip,related site,infomation site");
		req.setAttribute("check", check);
		try {
			req.getRequestDispatcher("/contact.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html");
		
		String[] check = new String[4];
		
		String name = req.getParameter("name");
	    String email = req.getParameter("email");
	    String text = req.getParameter("message");
		
	    if(name == null || (name != null && name.equals("")))
	    {
	    	check[0] = "Name is not empty";
	    }
	    java.util.regex.Pattern p = java.util.regex.Pattern.compile(".+@.+\\.[a-z]+");
	    Matcher m = p.matcher(email);
	    boolean matchFound = m.matches();

	    if (!matchFound)
	    {
	    	check[1] = "Invalid Email";
	    }
	    if(text == null || (text != null && text.equals("")))
	    {
	    	check[2] = "Message is not empty";
	    }
	    
		//check capchar
		String remoteAddr = req.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6LcF-80SAAAAAM2kArjyUwtVJYbH_DKredY3Q26U");

        String challenge = req.getParameter("recaptcha_challenge_field");
        String uresponse = req.getParameter("recaptcha_response_field");
        if(challenge == null)
        {
        	challenge = "b";
        }
        if(uresponse == null)
        {
        	uresponse = "a";
        }
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
        	check[3] = "Invalid Capchar";
        }
		if(check[0] == null && check[1] == null && check[2] == null && check[3] == null)
		{
			try {
	            URL url = new URL("http://www.firstping.com/toolmail");
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoOutput(true);
	            connection.setRequestMethod("POST");
	            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	            writer.write("email=chinhvd1984@gmail.com");
	            writer.write("&name_email="+email);
	            writer.write("&from_email=chinhvd1984@gmail.com");
	            writer.write("&subject=Mail contact from 5ty.org "+name);
	            writer.write("&content="+text);
	            writer.close();
	    
	            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            }
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			req.setAttribute("success", "Thanks for your contact");
		}
		req.setAttribute("check", check);
		req.setAttribute("title", "Contact us");
		req.setAttribute("description", "Contact us .firstping.com - We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
		req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site,add site,contact");
	    try {
			req.getRequestDispatcher("/contact.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

